﻿using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;
using System;

namespace Higgs.Web.AtomPub.Attributes
{
    /// <summary>
    /// Provide ability to solve ambiguous action methods problem in ASP.NET MVC.
    /// </summary>
    public class RequireParameterAttribute : ActionMethodSelectorAttribute 
    {
        public RequireParameterAttribute(string valueName, Type valueType)
        {
            ValueName = valueName;
            ValueType = valueType;
        }

        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            string rawString;

            if(controllerContext.RouteData.Values.ContainsKey(ValueName))
            {
                rawString = controllerContext.RouteData.Values[ValueName].ToString();
            }
            else
            {
                rawString = controllerContext.HttpContext.Request[ValueName];
            }

            if(rawString == null) return false;

            var converter = TypeDescriptor.GetConverter(ValueType);
            try
            {
                converter.ConvertFrom(rawString);
            }
            catch
            {
                return false;
            }

            return true;
        }

        public string ValueName { get; private set; }
        public Type ValueType { get; set; }
    }
}
